import cv2
import numpy as np

def rect_center_point(outer, inner):
    center_rect = [
        ((outer[0][0] + inner[0][0]) // 2, (outer[0][1] + inner[0][1]) // 2),
        ((outer[1][0] + inner[3][0]) // 2, (outer[1][1] + inner[3][1]) // 2),
        ((outer[2][0] + inner[2][0]) // 2, (outer[2][1] + inner[2][1]) // 2),
        ((outer[3][0] + inner[1][0]) // 2, (outer[3][1] + inner[1][1]) // 2)
    ]
    return np.array(center_rect, dtype=np.int32)

cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, 320)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 240)

while True:
    ret, frame = cap.read()
    if not ret:
        break

    gray_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray_img, 100, 200)

    _ ,contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    outer_rect = None
    inner_rect = None

    for contour in contours:
        area = cv2.contourArea(contour)
        if area > 100:  # 适当调整面积阈值
            epsilon = 0.02 * cv2.arcLength(contour, True)
            approx = cv2.approxPolyDP(contour, epsilon, True)
            if len(approx) == 4:
                if outer_rect is None or area > cv2.contourArea(outer_rect):
                    inner_rect = outer_rect
                    outer_rect = approx
                elif inner_rect is None or area > cv2.contourArea(inner_rect):
                    inner_rect = approx

    if outer_rect is not None and inner_rect is not None:
        # 打印外层矩形顶点
        print("外层矩形顶点坐标：", outer_rect.reshape(4, 2))
        # 打印内层矩形顶点
        print("内层矩形顶点坐标：", inner_rect.reshape(4, 2))
        # # 绘制外层和内层矩形
        # cv2.polylines(frame, [outer_rect], isClosed=True, color=(0, 255, 0), thickness=2)
        # cv2.polylines(frame, [inner_rect], isClosed=True, color=(255, 0, 0), thickness=2)
        # 计算并绘制中心矩形
        center_points = rect_center_point(outer_rect.reshape(4, 2), inner_rect.reshape(4, 2))
        print("中心矩形顶点坐标：", center_points)
        cv2.polylines(frame, [center_points], isClosed=True, color=(0, 0, 255), thickness=2)

    cv2.imshow("Frame", frame)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()
